import {Paging, Base} from "@/hooks/globalPageInterface";
import type {Request, _Paging, State} from "@/interfaces/components/Page";
import {ElMessage, ElMessageBox} from "element-plus";
import {ref} from "vue";
import {isArray} from "lodash";
import Login from "@/views/sys/log/login.vue";

//公共方法
function useTable(obj: Base<any, any> | Paging<any, any>, state: State<any, any>, getData: ()=> void){
    function del(id: string | number){
        ElMessageBox.confirm('确定进行删除操作? 此操作将会永久移除该数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(()=>{
            obj.del(id).then(res =>{
                ElMessage.success('删除成功')
                getData()
            })
        })

    }
    function batchDel(key: number | string | Array<string | number>){
        console.log("多选删除：", key)
        if(key === undefined || null || "") return
        let data: any[] = []
        if(isArray(key)){
            data = key
            if (data.length === 0) {
                ElMessage.warning('请选择删除记录')
                return
            }
        }else {
            data = [key]
        }
        ElMessageBox.confirm('确定进行删除操作? 此操作将会永久移除所选的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(()=>{
            obj.batchDel(data).then(res =>{
                ElMessage.success('删除成功')
                getData()
            })
        })
    }
    function update(data: any, fun?: ()=> void){
        obj.update(data).then(res =>{
            ElMessage.success('修改成功')
            getData()
            if(fun) fun()
        })
    }

    function added(data: any, fun?: ()=> void){
        console.log("新增：", data)
        obj.added(data).then(res =>{
            ElMessage.success('新增成功')
            getData()
            if(fun) fun()
        })
    }

    return {
        del, update, added, batchDel
    }
}

// 基础组件
export function useTableTemplate<T, D>(request: Request, state: State<T, D>, paging?: Paging<T, D>){
    const {createdIsNeed, url, fullUrl, responseProcessing} = request
    let base = new Base<T, D>(url, fullUrl || "", "GET")
    if(createdIsNeed) getData()

    function getData(){
        query(filterData<T>(state.queryForm), responseProcessing)
    }
    function query(params?:T, method?: (val: any)=> void){
        base.query(filterData<T>(params)).then(res =>{
            if(method !== undefined) method(res.data)
            state.dataList = res.data
        })
    }
    return {
        query, ...useTable(base, state, getData)
    }
}

// 分页组件
export function useTablePagingTemplate<T, D>(request: Request, state: State<T, D>){
    const {createdIsNeed, url, fullUrl, responseProcessing} = request
    const paging = new Paging<T, D>(url, fullUrl || "", "GET");
    let loading = ref(false);
    (()=>{
        const defData: _Paging = {
            page: 1,
            limit: 20,
            total: 0,
            pageSizes: [10, 20, 50, 100]
        }
        for (const key in defData) {
            if (!Object.getOwnPropertyDescriptor(state, key)) {
                /** 有待优化 */
                setProperties(state, key as keyof typeof state, defData[key as keyof typeof defData])
            }
        }
    })()
    if(createdIsNeed) getData()

    function getData(){
        query(filterData<T>(state.queryForm), responseProcessing)
    }
    /**
     * 分页查询
     * @param params
     * @param method
     */
    function query(params?:T, method?: (val: any)=> void){
        console.log("分页查询")
        loading.value = true
        paging.query({
            page: state.page,
            limit: state.limit,
        },filterData<T>(params)).then(res =>{
            loading.value = false
            if(method !== undefined) method(res.data.list || res.data.records)
            state.dataList = res.data.list || res.data.records
            state.total = res.data.total
        })
    }

    /**
     * 分页组件页大小改变
     * @param val
     */
    function handleSizeChange(val: number){
        state.limit = val
        query(filterData<T>(state.queryForm))
    }

    /**
     * 分页组件当前页码发生变化
     * @param val
     */
    function handleCurrentChange(val: number){
        console.log(`current page: ${val}`)
        state.page = val
        query(filterData<T>(state.queryForm))
    }

    return {
        query, handleSizeChange, handleCurrentChange, loading, ...useTable(paging, state, getData)
    }
}

function setProperties<T, K extends keyof T, V extends T[K]>(obj: T, key: K, value: V){
    obj[key] = value;
}

/**
 * 过滤数据，去除掉值为空或空字符串的数据
 * @param params
 */
function filterData<T>(params: any):T | undefined{
    if (params === undefined) return
    for(let key in params){
        if(!params[key]) delete params[key]
    }
    return params
}


